var express = require('express');
var BlogPost = require('../domain/BlogPost');
var co = require('co');

var router = express.Router();

var blogPost = new BlogPost();
/**
 * 博客发布页
 */
router.get('/add', function (req, res, next) {
    res.render('admin/add');
});

router.post('/save', function (req, res, next) {

    if (!req.body.title || !req.body.contentHtml || !req.body.contentMarkdown) {
        res.redirect("/admin/posts/add");
        return;
    }
    let contentMarkdown = req.body.contentMarkdown;
    let summary = contentMarkdown.substring(0, 100);
    let params = [req.body.title, req.body.contentHtml, contentMarkdown,summary , 1];
    co(function *() {
        var result = yield blogPost.saveByParams(params);
        res.redirect(`/posts/${result.insertId}`);
    });

});

router.get('/edit/:id', (req, res, next)=> {
    co(function *() {
        var result = yield blogPost.findOne(req.params.id);
        res.render('admin/edit', {blogPost: result[0]});
    });

});

router.post('/update', function (req, res, next) {

    if (!req.body.id || !req.body.title || !req.body.contentHtml || !req.body.contentMarkdown) {
        res.redirect("/");
        return;
    }
    let contentMarkdown = req.body.contentMarkdown;
    let summary = contentMarkdown.substring(0, 100);
    let params = [req.body.title, req.body.contentHtml, contentMarkdown,summary , req.body.id];
    co(function *() {
        yield blogPost.updateByParams(params);
        res.redirect(`/posts/${req.body.id}`);
    });

});

module.exports = router;
